package leetcode;

import java.util.ArrayList;

/**
 * Created by Ghost on 2014/12/2 0002.
 */
public class Longest_Common_Prefix {
    public String longestCommonPrefix(String[] strs) {
        if(strs==null || strs.length==0)
            return "";
        if(strs.length==1)
            return strs[0];
        ArrayList<char[]> list = new ArrayList<char[]>(strs.length);
        int minIdx = Integer.MAX_VALUE;

        for(String str:strs){
            list.add(str.toCharArray());
            minIdx = minIdx>str.length()?str.length():minIdx;
        }
        StringBuilder stringBuilder = new StringBuilder("");
        boolean equal = true;
        for(int i=0;i<minIdx;i++){
            if(equal){
                char tmp = list.get(0)[i];
                for(int j = 1;j<list.size();j++){
                    equal = tmp==list.get(j)[i];
                    if(!equal)
                        break;
                }
                if(equal)
                    stringBuilder.append(tmp);
            }
            else{
                break;
            }
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args){
        Longest_Common_Prefix longest_common_prefix = new Longest_Common_Prefix();
        String[] strs = new String[4];
        strs[0] = "abcde";
        strs[1] = "abcde";
        strs[2] = "abcde";
        strs[3] = "abcde";

        System.out.println(longest_common_prefix.longestCommonPrefix(strs));
    }
}
